package algorithm_demo.demo01;

import java.util.Arrays;

/**
 * 选择排序
 * 每次遍历找到最小值，
 * 0 - N-1;
 * 1 - N-1;
 * 2 - N-1;
 * ........
 * N-2 - N-1;
 *
 * @author Api
 * @date 2023/1/25 20:51
 */
public class Code07_SelectSort {
    public static void main(String[] args) {
        int[] arr = {4,2,1,4,4,5,5,6,3,1};
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
    }


    public static void selectionSort(int[] arr) {
        //临界值
        if (arr == null || arr.length < 2) {
            return;
        }
        /*
        * 0 - N-1
        * 1 - N-1
        * 2 - N-1
        * 3 - N-1
        * 4 - N-1
        * */
        int N = arr.length;
        for (int i = 0; i < N; i++) {
            int minValueIndex = i;//最小值下标
            //每次遍历找到剩余最小值的下标
            for (int j = i + 1; j < N; j++) {
                minValueIndex = arr[minValueIndex] > arr[j] ? j : minValueIndex;
            }
            swap(arr, i, minValueIndex);
        }
    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
}
